package com.study.controller;

import com.study.async.AsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@Slf4j
public class AsyncController {

    @Autowired
    private AsyncTask asyncTask;

    @RequestMapping("/async")
    public String async() throws InterruptedException, ExecutionException {
        Long time = System.currentTimeMillis();

        Future<String> doTask1 = asyncTask.doTask1();
        Future<String> doTask2 = asyncTask.doTask2();
        while (true) {
            if (doTask1.isDone() && doTask2.isDone()) {
                log.info("Task1 result: {}", doTask1.get());
                log.info("Task2 result: {}", doTask2.get());
                break;
            }
            Thread.sleep(1000);
        }

        log.info("耗時：{} ms", System.currentTimeMillis() - time);
        return "success";
    }

    @Async
    @RequestMapping("/async1")
    public String async1() throws InterruptedException, ExecutionException {
        Long time = System.currentTimeMillis();


        Thread.sleep(1000);

        log.info("耗時：{} ms", System.currentTimeMillis() - time);
        return "success";
    }
}
